﻿/*******************************************************************************
* Copyright (C) sykjwh.cn
* 
* Author: liuxiang
* Create Date: 2018/03/08 
* Description: Automated building by liuxiang20041986@qq.com 
* http://www.sykjwh.cn/
*********************************************************************************/
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System.IO;

namespace Sykj.Infrastructure
{
    /// <summary>
    /// 读取指定配置文件
    /// </summary>
    public class ConfigurationManager
    {
        /// <summary>
        /// 获取Configuration的实例
        /// </summary>
        public readonly static IConfiguration Configuration;

        static ConfigurationManager()
        {
            Configuration = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json", optional: true)
               .Build();
        }

        /// <summary>
        /// 读取Section节点
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T GetSection<T>(string key) where T : class, new()
        {
            var obj = new ServiceCollection()
                .AddOptions()
                .Configure<T>(Configuration.GetSection(key))
                .BuildServiceProvider()
                .GetService<IOptions<T>>()
                .Value;
            return obj;
        }

        /// <summary>
        /// 读取Section节点
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetSection(string key)
        {
            return Configuration.GetValue<string>(key);
        }
    }
}
